package processor

import (
	"chat-room/common"
	"encoding/json"
	"errors"
	"fmt"
	"net"
)

type Processor struct {
	Conn net.Conn
}

//处理每一个客户端连接
func (that *Processor) Handel (){
	functionsEx := &common.Functions{}
	for {
		msg, err := functionsEx.ReadMsg(that.Conn)
		if err != nil {
			fmt.Printf("functionsEx.ReadMsg:%v\n",err)
			return
		}else{
			err = that.HandOut(msg)
			if err != nil {
				fmt.Printf("Processor.HandOut:%v\n",err)
			}
		}
	}
}

//根据消息类型调用对应方法
func (that *Processor) HandOut (msg *common.Message) (err error) {
	switch msg.Type {
		case common.LoginRequestMsgType:
			fmt.Printf("%v:正在进行登录操作\n",that.Conn.RemoteAddr())
			//登录
			var LoginRequestMsg *common.LoginRequestMsg
			_ = json.Unmarshal([]byte(msg.Data),&LoginRequestMsg)
			userEx := &User{
				Conn:that.Conn,
			}
			userEx.Login(LoginRequestMsg.Account, LoginRequestMsg.Password)
			return
		case common.RegisterRequestMsgType:
			//注册
			fmt.Printf("%v:正在进行注册操作\n",that.Conn.RemoteAddr())
			var RegisterRequestMsg *common.RegisterRequestMsg
			_ = json.Unmarshal([]byte(msg.Data),&RegisterRequestMsg)
			userEx := &User{
				Conn:that.Conn,
			}
			userEx.Register(RegisterRequestMsg.Account, RegisterRequestMsg.Password, RegisterRequestMsg.Name)
			return
		case common.GetOnlineUsersRequestMsgType:
			//获取在线用户
			userEx := &User{
				Conn:that.Conn,
			}
			userEx.GetOnlineUsers()
			return
		case common.MassMessageRequestMsgType:
			//群发消息
			fmt.Printf("%v:正在进行群发消息操作\n",that.Conn.RemoteAddr())
			MessageEx := &Message{
				Conn:that.Conn,
			}
			MessageEx.MassMessage(msg.Data)
			return
		default:
			err = errors.New("消息类型错误")
	}
	return
}